package com.zmn.oms.business.impl.master;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.zmn.base.engineer.common.constants.DubboConsts;
import com.zmn.base.engineer.common.dro.foreign.engineer.ForeignEngineerBasicInfoDRO;
import com.zmn.base.engineer.common.dro.foreign.engineer.ForeignEngineerDetailInfoDRO;
import com.zmn.base.engineer.dubbo.interfaces.foreign.EngineerListRemoteService;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.oms.business.interfaces.master.OrderMasterBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.master.MasterSharingDTO;
import com.zmn.oms.model.dto.master.SharingInfo;
import com.zmn.oms.model.entity.master.OrderMaster;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.master.OrderMasterService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：工程师
 * @author liuying
 * @date 2018/12/11 14:27
 */
@Service
public class OrderMasterBServiceImpl implements OrderMasterBService {

    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private EngineerListRemoteService engineerListRemoteService;
    //@Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    //private RoleListRemoteService roleListRemoteService;

    private Logger logger = LoggerFactory.getLogger(OrderMasterBServiceImpl.class);

    @Autowired
    private OrderMasterService orderMasterService;

    @Override
    public void insertOrderMaster(OrderMaster orderMaster) throws OmsBaseException {
        this.findMasterInfo(orderMaster);
        orderMasterService.insertOrderMaster(orderMaster);
    }

    @Override
    public void insertAll(List<OrderMaster> orderMasters) throws OmsBaseException {
        if (CollectionUtils.isEmpty(orderMasters)) {
            return;
        }

        this.listMasterInfo(orderMasters);
        orderMasterService.insertAll(orderMasters);
    }

    private void listMasterInfo(List<OrderMaster> orderMasterList) throws OmsBaseException {

        Set<Integer> masterIdList = orderMasterList.stream()
                .filter(e -> StringUtils.isBlank(e.getMasterName()))
                .map(OrderMaster::getMasterId)
                .collect(Collectors.toSet());
        if (CollectionUtils.isEmpty(masterIdList)) {
            return;
        }
        logger.info("listMasterInfo#listEngineerByIdSet 入参 [{}]",masterIdList);
        ResponseDTO<List<ForeignEngineerBasicInfoDRO>> listResponseDTO = engineerListRemoteService.listEngineerByIdSet(masterIdList);
        logger.info("listMasterInfo#listEngineerByIdSet 出参 [{}]", listResponseDTO);
        if (!listResponseDTO.isSuccess() || listResponseDTO.getData() == null) {
            throw new OmsBaseException("工程师信息不存在");
        }

        Map<Integer, ForeignEngineerBasicInfoDRO> engineerBasicInfoDROMap = Maps.uniqueIndex(listResponseDTO.getData(), ForeignEngineerBasicInfoDRO::getEngineerId);

        for (OrderMaster orderMaster : orderMasterList) {
            if (!StringUtils.isBlank(orderMaster.getMasterName())) {
                continue;
            }
            ForeignEngineerBasicInfoDRO dro = engineerBasicInfoDROMap.get(orderMaster.getMasterId());
            if (Objects.isNull(dro)) {
                continue;
            }
            orderMaster.setMasterName(dro.getRealName());
            orderMaster.setMasterPhone(dro.getMobile());
        }

    }

    private void findMasterInfo(OrderMaster orderMaster) throws OmsBaseException {

        // 查询工程师信息2020年06月02日18:29:57 （更新接口）
        if (StringUtils.isBlank(orderMaster.getMasterName())) {
            // todo fubiao
            logger.info("findMasterInfo#getEngineerDetailById 入参 [{}]",orderMaster.getMasterId());
            ResponseDTO<ForeignEngineerDetailInfoDRO> cacheEngineerByEngineerId = engineerListRemoteService.getEngineerDetailById(orderMaster.getMasterId());
            logger.info("findMasterInfo#getEngineerDetailById 出参 [{}]", JSON.toJSONString(cacheEngineerByEngineerId));
            if (!cacheEngineerByEngineerId.isSuccess() || cacheEngineerByEngineerId.getData() == null) {
                throw new OmsBaseException("工程师信息不存在");
            }

            ForeignEngineerDetailInfoDRO mastMasterDRO = cacheEngineerByEngineerId.getData();
            orderMaster.setMasterName(mastMasterDRO.getRealName());
            orderMaster.setMasterPhone(mastMasterDRO.getMobile());
        }
    }

    @Override
    @Transactional
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_MASTER_SHARE)
    public int updateOrderMasterShare(MasterSharingDTO masterSharingDTO) throws OmsBaseException {
        for (SharingInfo sharingInfo : masterSharingDTO.getSharingInfoList()) {
            OrderMaster master = BeanMapper.map(sharingInfo, OrderMaster.class);
            master.setOrderId(masterSharingDTO.getOrderId());

            master.setUpdater(masterSharingDTO.getOperator());
            master.setUpdateTime(DateUtil.getNow());

            orderMasterService.updateMasterShare(master);
        }
        return masterSharingDTO.getSharingInfoList().size();
    }

    @Override
    public boolean checkMasterSharing(OrderWork orderWork) {
        List<OrderMaster> orderMasters = orderMasterService.listMasterByWorkId(orderWork.getOrderId(), orderWork.getWorkId());
        Integer totalShare = orderMasters.stream().mapToInt(master -> {
            return Optional.ofNullable(master.getShareRate()).orElse(0);
        }).sum();
        return totalShare == 10000;
    }

    @Override
    public Map<Integer, String> listMasterIdentityMap(List<Integer> masterIdList) {
        Map<Integer, String> identityMap = Maps.newHashMapWithExpectedSize(masterIdList.size());

        try {
            if (CollectionUtils.isNotEmpty(masterIdList)) {
                masterIdList.forEach(masterId -> {
                    if (NumberUtil.isNotNullOrZero(masterId) && !identityMap.containsKey(masterId)) {
                        logger.info("listMasterIdentityMap#checkIsStudent 入参 [{}]", masterId);
                        ResponseDTO<Boolean> responseDTO = engineerListRemoteService.checkIsStudent(masterId);
                        logger.info("listMasterIdentityMap#checkIsStudent 出参 [{}]", JSON.toJSONString(responseDTO));
                        if (responseDTO.isSuccess() && responseDTO.getData()) {
                            identityMap.put(masterId, "学徒");
                        } else {
                            identityMap.put(masterId, "工程师");
                        }
                    }
                });
            }
        } catch (Exception ex) {

        }

        return identityMap;
    }
}
